using System;
using System.ComponentModel;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using AvaloniaApplicationDemo.ViewModels;
using Microsoft.Extensions.DependencyInjection;

namespace AvaloniaApplicationDemo;

public class ViewLocator : IDataTemplate
{
    // 服务提供者 保存服务提供器实例
    private static IServiceProvider _serviceProvider;

    // 根据 ViewModel 创建对应的 View
    public Control Build(object? viewModel)
    {
        if (viewModel == null)
            return new TextBlock { Text = "ViewModel is null" };

        return viewModel switch
        {
            // 其他 ViewModel -> View 映射...
            _ => CreateViewByConvention(viewModel)
        };
    }

    public bool Match(object? data)
    {
        return data is INotifyPropertyChanged;
    }

    // 初始化服务提供者，注入IServiceProvider
    public static void Initialize(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// 自动根据 ViewModel 名称自动匹配 View（约定：ViewModel 名称替换为 View）
    /// </summary>
    private static Control CreateViewByConvention(object viewModel)
    {
        var viewModelType = viewModel.GetType();
        // 获取 ViewModel 的完整命名空间
        var viewModelNamespace = viewModelType.Namespace ??
                                 throw new InvalidOperationException("ViewModel has no namespace.");
        // 替换命名空间中的 ViewModel -> View
        var viewNamespace = viewModelNamespace.Replace("ViewModels", "Views");

        var viewName = viewModelType.Name.Replace("ViewModel", "View");


        // 构造可能的 View 类型（在 Views 命名空间下）
        var fullViewTypeName = $"{viewNamespace}.{viewName}";

        var viewType = viewModelType.Assembly.GetType(fullViewTypeName);

        if (viewType != null && typeof(Control).IsAssignableFrom(viewType))
            return (Control)_serviceProvider.GetRequiredService(viewType);

        // 如果未找到对应 View，返回提示信息
        return new TextBlock { Text = $"No view found for {viewModelType.Name}" };
    }
}